package com.huazi.eduorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huazi.commonutils.CourseOrder;
import com.huazi.commonutils.MemberOrder;
import com.huazi.eduorder.entity.TOrder;
import com.huazi.eduorder.feginclient.CourseClient;
import com.huazi.eduorder.feginclient.MemberClient;
import com.huazi.eduorder.mapper.TOrderMapper;
import com.huazi.eduorder.service.TOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huazi.eduorder.utils.RandomOrderNo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author huazi
 * @since 2021-03-30
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {
    //生成购物车订单，返回订单号
    @Autowired
    MemberClient memberClient;
    @Autowired
    CourseClient courseClient;
    @Override
    public TOrder createOrders(String courseId, String memberId, List<String> list) {
        //先判断之前是否购买过此课程的未支付订单
        TOrder tOrder = baseMapper.selectOne(new QueryWrapper<TOrder>().eq("course_id", courseId).eq("member_id", memberId).eq("status", 0));
        if(tOrder==null){//没有则添加订单信息，有则直接返回此订单
            tOrder=new TOrder();
            //远程调用获取课程信息
            CourseOrder courseOrderInfo = courseClient.getCourseOrderInfo(courseId);
            System.out.println("远程调用课程："+courseOrderInfo);
            if(courseOrderInfo.getId()==null){//判断远程调用是否成功
                tOrder.setCourseId(null);
                return tOrder;
            }
            //远程调用获取用户信息
            MemberOrder memberOrderInfo = memberClient.getMemberOrderInfo(memberId);
            System.out.println("远程调用用户："+memberOrderInfo);
            if(memberOrderInfo.getId()==null){
                tOrder.setMemberId(null);
                return tOrder;
            }
            tOrder.setCourseCover(courseOrderInfo.getCover())//课程封面
                    .setCourseId(courseId)//课程id
                    .setCourseTitle(courseOrderInfo.getTitle())//课程名称
                    .setMemberId(memberOrderInfo.getId())//用户id
                    .setNickname(memberOrderInfo.getNickname())//用户昵称
                    .setTeacherName(courseOrderInfo.getTeacherName())//讲师昵称
                    .setStatus(0)//订单状态
                    .setPayType(1).setIsDeleted(false).setTotalFee(courseOrderInfo.getPrice());//支付类型
            //生成订单号
            String orderNo = RandomOrderNo.getOrderNo();
            tOrder.setOrderNo(orderNo);//订单号
            baseMapper.insert(tOrder);//订单信息存入数据库
            list.add("yes");//如果是添加则添加一个值
        }
        return tOrder;
    }
    //修改订单状态
    @Override
    public int orderStatus(String memberId) {
        return baseMapper.orderStatus(memberId);
    }
}
